package com.wude.guild.views;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.blankj.utilcode.util.ToastUtils;
import com.mc.developmentkit.utils.ToastUtil;
import com.wude.bean.ChoujiangBean;
import com.wude.guild.GameDetActivity;
import com.wude.guild.LoginActivity;
import com.wude.guild.R;
import com.wude.guild.dialog.GetCouponDialog;
import com.wude.guild.face.LuckViewFace;
import com.wude.guild.servercore.mints.TitleBaseFragment;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.ImageUtils;
import com.wude.tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/11/20 0020.
 */

public class LuckPanView extends ScrollView implements LuckPanLayout.AnimationEndListener {
    private Activity activity;
    private TitleBaseFragment fragment;
    private Context context;

    private LuckPanLayout luckPanLayout;
    private ViewFlipper homepage_notice_vf;

    private String[] strs;
    private List<Bitmap> bitmaps = new ArrayList<>();
    private List<String> imgUrls = new ArrayList<>();
    /**
     * 刷新抽奖次数和中奖名单
     */
    private Handler imgHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 1) {
                setViews();
                HttpCom.POST(mhandler, HttpCom.getGetLotteryList(), new HashMap<String, String>(), false);
            }
            return false;
        }
    });
    private String giftName;//本次抽奖中奖信息
    //滚动通知中奖信息
    private int mCurrPos;
    private List<String> titleList;
    private Timer timer;
    private static final int MESSAGE_LOGIN = 1;
    /**
     * 中奖名单通知滚动
     */
    @SuppressLint("HandlerLeak")
    private Handler noticeHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == MESSAGE_LOGIN) {
                moveNext();
            }
            return true;
        }
    });
    private TextView tv_noticeTitle;//免费/5M
    private TextView tv_noticeCount;//还剩3次
    private View startButton;
    private RelativeLayout rv_content;
    private LuckViewFace face;
    private String phone;

    private String game_name;
    private String giftbag_name;
    private String desribe;
    private String game_id;

    public LuckPanView(Context context, Activity activity, LuckViewFace face) {
        super(context);
        this.activity = activity;
        this.context = context;
        this.face = face;
        initView();
    }

    public LuckPanView(Context context, Activity activity, String phone) {
        super(context);
        this.activity = activity;
        this.context = context;
        this.phone = phone;
        initView();
    }

    public LuckPanView(Context context, TitleBaseFragment fragment) {
        super(context);
        this.fragment = fragment;
        this.context = context;
        initView();
    }

    public LuckPanView(Context context, TitleBaseFragment fragment, LuckViewFace face) {
        super(context);
        this.fragment = fragment;
        this.context = context;
        this.face = face;
        initView();
    }

    private void initView() {
        LayoutInflater.from(context).inflate(R.layout.lackpan_view, this);
        luckPanLayout = findViewById(R.id.luckpan_layout);
        homepage_notice_vf = findViewById(R.id.homepage_notice_vf);
        tv_noticeTitle = findViewById(R.id.tv_noticeTitle);
        tv_noticeCount = findViewById(R.id.tv_noticeCount);
        rv_content = findViewById(R.id.rv_content);

        Map<String, String> dataMap = new HashMap<>();
        HttpCom.POST(handler, HttpCom.getGetLottery(), dataMap, false);
    }

    public void canGoOn(boolean goon) {
        if (goon) {
            startButton.setClickable(true);
        } else {
            startButton.setClickable(false);
        }
    }

    //转盘图片下载
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    ArrayList<ChoujiangBean> beans = HttpUtils.DNSChoujiang(msg.obj.toString());
                    try {
                        initData(beans);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showLongToast("图片加载失败！");
                    }
                    break;
                case 2:
                    ToastUtils.showLongToast("网络异常！");
                    break;
            }
        }
    };

    private void initData(List<ChoujiangBean> dataBean) throws Exception {
        if (dataBean != null && dataBean.size() != 0) {
            if (strs == null)
                strs = new String[dataBean.size()];
            for (int i = 0; i < dataBean.size(); i++) {
                ChoujiangBean data = dataBean.get(i);
                strs[i] = data.name;
                imgUrls.add(data.icon);
            }
        }
        StartDown(imgUrls);
    }

    //下载
    protected void StartDown(final List<String> urls) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < urls.size(); i++) {
                    Bitmap bitmap = ImageUtils.netPicToBmp(urls.get(i));
                    bitmaps.add(bitmap);
                    if (i == urls.size() - 1) {
                        Message message = new Message();
                        message.what = 1;
                        imgHandler.sendMessage(message);
                    }

                }
            }
        }).start();
    }

    private void setViews() {
        rv_content.setVisibility(VISIBLE);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        RotatePan rotatePan = new RotatePan(getContext(), bitmaps.size(), strs, bitmaps);
        rotatePan.setLayoutParams(params);

        startButton = LayoutInflater.from(getContext()).inflate(R.layout.zhuanpan_item, null);
        startButton.setClickable(true);
        startButton.setTag("startbtn");
        startButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.getLoginUser() == null) {
                    if (fragment != null)
                        fragment.startActivityForResult(new Intent(fragment.getActivity(), LoginActivity.class), 11);
                    else if (activity != null)
                        activity.startActivityForResult(new Intent(activity, LoginActivity.class), 11);
                } else {
//                    rotation();
                    if (face != null) {
                        face.isFirst();
                        startButton.setClickable(false);
                    } else {//face为空，说明是从活动过来的
                        rotation();
                    }
                }
            }
        });

        if (luckPanLayout.getChildCount() > 0) {
            luckPanLayout.removeAllViews();
        }
        luckPanLayout.addView(rotatePan);
        luckPanLayout.addView(startButton);

        luckPanLayout.setAnimationEndListener(this);
    }

    public void rotation() {
        //请求中奖信息
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("token", Utils.getLoginUser().token);
        dataMap.put("bindphone", phone);
        HttpCom.POST(zhandler, HttpCom.getGetLotteryPrize(), dataMap, false);
//        luckPanLayout.rotate(-1, 100);
    }

    @SuppressLint("HandlerLeak")
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //刷新抽奖次数
//                    try {
//                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
//                        JSONObject data = jsonObject.getJSONObject("data");
//                        int num = data.getInt("num");
////                        setStartButton(num);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                    //刷新中奖名单
                    titleList = HttpUtils.DNSNoticeItem(msg.obj.toString());
                    if (titleList != null && titleList.size() != 0) {
                        TimerTask task = new TimerTask() {
                            @Override
                            public void run() {
                                noticeHandler.sendEmptyMessage(MESSAGE_LOGIN);
                                Log.d("Task", "下一个");
                            }
                        };
                        timer = new Timer();
                        timer.schedule(task, 0, 4000);
                    }
                    break;
                case 2:
                    break;
            }
        }
    };

    private void setStartButton(int count) {

        if (startButton != null) {
            startButton.setClickable(true);
        }
        if (count == 3) {
            tv_noticeTitle.setText("免费");
        } else if (count < 3 && count > 0) {
            tv_noticeTitle.setText("5M");
        } else if (count == 0) {
            tv_noticeTitle.setText("5M");
            tv_noticeTitle.setTextColor(getContext().getResources().getColor(R.color.t808080));
            tv_noticeCount.setTextColor(getContext().getResources().getColor(R.color.t808080));
        }
        tv_noticeCount.setText("还剩" + count + "次");
    }

    private void moveNext() {
        setNoticeView(mCurrPos, mCurrPos + 1);
        homepage_notice_vf.setInAnimation(getContext(), R.anim.in_bottomtop);
        homepage_notice_vf.setOutAnimation(getContext(), R.anim.out_bottomtop);
        homepage_notice_vf.showNext();
    }

    private void setNoticeView(int curr, int next) {
        View noticeItem = LayoutInflater.from(getContext()).inflate(R.layout.notice_item, null);
        TextView tvNotice = noticeItem.findViewById(R.id.notice_tv);
        if ((curr < next) && (next > (titleList.size() - 1))) {
            next = 0;
        } else if ((curr > next) && (next < 0)) {
            next = titleList.size() - 1;
        }

        //titleList.get(next)
        tvNotice.setText(titleList.get(next));
        tvNotice.setPadding(0, 0, 0, 0);
        if (homepage_notice_vf.getChildCount() > 1) {
            homepage_notice_vf.removeViewAt(0);
        }

        homepage_notice_vf.addView(noticeItem, homepage_notice_vf.getChildCount());
        mCurrPos = next;
    }

    @SuppressLint("HandlerLeak")
    Handler zhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        String status = jsonObject.getString("status");
                        if ("-1".equals(status)) {
                            ToastUtil.showToast(jsonObject.getString("return_code") + "");
//                            setStartButton(0);
                            break;
                        }
                        JSONObject data = jsonObject.getJSONObject("data");
                        giftName = data.getString("name");
                        luckPanLayout.rotate(data.getInt("position"), 100);

                        if (face == null) {
                            game_name = data.getString("game_name");
                            giftbag_name = data.getString("giftbag_name");
                            desribe = data.getString("desribe");
                            game_id = data.getString("game_id");
//                            jumpt(game_name, giftbag_name, desribe, game_id);
                            break;
                        }

                        //刷新中奖名单和次数
                        HttpCom.POST(mhandler, HttpCom.getGetLotteryList(), new HashMap<String, String>(), false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    ToastUtils.showLongToast("网络异常！");
                    startButton.setClickable(true);
                    break;
            }
        }
    };

    private void jumpGameDet() {
        final GetCouponDialog dialog = new GetCouponDialog(context, game_name + giftbag_name, desribe, "立即使用");
        dialog.show();

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (activity != null)
                    activity.finish();
            }
        });

        dialog.getButton().setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, GameDetActivity.class);
                intent.putExtra("id", game_id);
                context.startActivity(intent);
                dialog.dismiss();
            }
        });
    }

    @Override
    public void endAnimation(int position) {
        if (face == null) {
            jumpGameDet();
            return;
        }
        ToastUtils.showLongToast(giftName);
        startButton.setClickable(true);
    }

    public void refresh() {
        HttpCom.POST(mhandler, HttpCom.getGetLotteryList(), new HashMap<String, String>(), false);
    }
}
